package com.erpoa.service.impl;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.erpoa.annotation.DataBase;
import com.erpoa.constants.DataSourceNames;
import com.erpoa.constants.MqConstant;
import com.erpoa.entity.*;
import com.erpoa.mapper.CarDataMapper;
import com.erpoa.service.CacheService;
import com.erpoa.service.CarDataService;
import com.erpoa.service.MsgService;
import com.erpoa.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.annotations.Cacheable;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: jamin.chen
 * @createDate: 2020/1/7 10:22
 * @version: 1.0
 */

@Service
public class CarDataServiceImpl implements CarDataService {
    private static final Logger logger = LoggerFactory.getLogger(CarDataServiceImpl.class);
    @Autowired
    private CarDataMapper carDataMapper;

    @Autowired
    private CacheService cacheService;

    @Resource
    private RedisUtil redisUtil;

    @Value("${spring.redis.reidsexpire}")
    private Long reidsexpire;

    @Autowired
    private MsgService msgService;

    /**
     *
     * @param carData
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @DataBase(DataSourceNames.WMS)
    public RespPageEntity fetchCarData(CarData carData, Integer pageNum, Integer pageSize) {
        RespPageEntity pageEntity = new RespPageEntity();
        // 默认从0开始
        if (pageSize != null && pageSize != null) {
            pageNum = (pageNum-1)*pageSize;
        }
        // 获取当前也用户信息
        List<CarData> carDatas = carDataMapper.queryCarDataList(carData.getCarNo(),carData.getTrayNo());
        pageEntity.setData(carDatas);
        Long total = carDataMapper.getTotal(carData.getCarNo(),carData.getTrayNo());
        pageEntity.setTotal(total);
        return pageEntity;

    }


    /**
     *
     * @param carNo
     * @param trayNos
     * @return
     */
    @DataBase(DataSourceNames.WMS)
    @Transactional
    @Override
    public int updTrayData(String carNo,List trayNos) {
        Map params = new HashMap();
        params.put("carNo",carNo);
        params.put("trayNos",trayNos);
       return carDataMapper.updTrayData(params);
    }

    @DataBase(DataSourceNames.WMS)
    @Transactional
    @Override
    public int countTrayData(CarData carData) {
        return carDataMapper.countTrayData1(carData.getCarNo(),carData.getTrayNo());
    }

    @Cacheable(value = "#mbarCode+'hasDetail'")
    private LogicBean hasDetail(String mBarcode) {
        return this.carDataMapper.selectHasDetailSqlBybarCode(mBarcode);
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject checkWuLiuFaHuoByBarcodeFirst(PackMessageByWuLiu packMessage) throws PDAException, SQLException {
        String mBarcode = packMessage.getBarcode();
        String userCode = packMessage.getUser().getsCode();
        String mPckBarCode = packMessage.getMpckBarCode();
        JSONObject obj = new JSONObject();
        String trayNo="1";
        LogicBean logicBean ;
        int rowdetail = 0;
        logger.debug("checkWuLiuFaHuoByBarcodeFirst：" + packMessage.toString());
        try {
            if (redisUtil.hasKey(mBarcode)) {
                logicBean = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(mBarcode)), LogicBean.class);
            } else {
                logicBean = carDataMapper.selectBaseLogicBeanByMBarcode(mBarcode);
                if(null==logicBean){
                    throw new PDAException("当前物流码" + mBarcode + "未拉取到明细数据，请手动更新数据或者确认日期和已出标签后再操作一次!");
                }
                logicBean.setLogisticNo(mBarcode);
                redisUtil.set(mBarcode, JSONUtil.toJsonStr(logicBean), reidsexpire);
            }


            //复核箱码和条码是否贴错
            if (!mPckBarCode.equals(logicBean.getPckBarcode())) {
                ProdPack prodPack = null;
                if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo())) {
                    prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo())), ProdPack.class);
                } else {
                    prodPack = carDataMapper.selectprodPackQueryByParam(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                    if (null == prodPack) {
                        if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo() + "like")) {
                            prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo() + "like")), ProdPack.class);
                        } else {
                            prodPack = carDataMapper.selectprodPackQueryByParamlike(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                            if (null == prodPack) {
                                throw new PDAException("First:当前外箱码不匹配，请人工核查外箱与物流码一致性！");
                            }
                            redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo() + "like", prodPack, reidsexpire);
                        }
                    }
                }

                if (!mPckBarCode.equals(prodPack.getPckBarcode())) {
                    redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo());
                    redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo() + "like");
                    throw new PDAException("second:当前外箱码不匹配，请人工核查外箱与物流码一致性！");
                }
                //开始比对
                if (!logicBean.getProdNo().trim().equals(prodPack.getProdNo().trim())) {
                    throw new PDAException("当前：" + logicBean.getOrgNo() + "当前外箱对应货物:" + logicBean.getProdName() + "与物流码对应货物型号：" + prodPack.getProdNo() + "不匹配，请联系相关人员!");
                }
                if (!new Integer(prodPack.getPckQty()).equals(new Integer(logicBean.getLogisticQty()))) {
                    if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo() + "like")) {
                        prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo() + "like")), ProdPack.class);
                    } else {
                        prodPack = carDataMapper.selectprodPackQueryByParamlike(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                    }
                    if (null == prodPack) {
                        throw new PDAException("当前：" + logicBean.getOrgNo() + "当前外箱对应最大规格数量：" + prodPack.getPckQty() + "与物流码对应数量需求" + logicBean.getLogisticQty() + "不匹配，请联系相关人员!");
                    } else {
                        redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo() + "like", prodPack, reidsexpire);
                        if (!new Integer(prodPack.getPckQty()).equals(new Integer(logicBean.getLogisticQty()))) {
                            redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo() + "like");
                            redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo());
                            throw new PDAException("当前：" + logicBean.getOrgNo() + "当前外箱对应最大规格数量：" + prodPack.getPckQty() + "与物流码对应数量需求" + logicBean.getLogisticQty() + "不匹配，请联系相关人员!");
                        }
                    }
                }
                logicBean.setPckQty(prodPack.getPckQty().toString());
                logicBean.setTrayDesc("0");
            }

            LogicBean logicBeanTrayNumber = hasDetail(mBarcode);
            //先查询箱规
            ReviewLine  reviewLine = this.carDataMapper.selectSqlLineBybarCode(logicBean);
            // logicBean.setUnDft(reviewLine.getUnDft());
            if (null!=logicBeanTrayNumber&&logicBeanTrayNumber.getTrayNumber().length()!=0) {
                //TODO CJM
                logicBean.setHttpResponse("当前物流码："+mBarcode+",已复核过!");
                logicBean.setTrayNumber(logicBeanTrayNumber.getTrayNumber());
            } else {
                Object cache = cacheService.getCommonCache(logicBean.getsName() + userCode + "trayNo");
                if (StringUtil.isNotNull(cache)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
                    trayNo = cache.toString();
                    if (trayNo == "1") {
                        //cacheService.cleanCommonCache(logicBean.getsName()+userCode+"trayNo");
                        //生产托盘号，按天重复生成
                        String traySqlCountResult = this.carDataMapper.selectTraySqlCount(logicBean.getsName(), userCode, sdf.format(new Date()));
                        BigInteger trayCount = null;
                        if (StringUtil.isEmpty(traySqlCountResult)) {
                            trayCount = new BigInteger("1");
                        } else {
                            trayCount = new BigInteger(traySqlCountResult);
                        }
                        if ("1".equals(trayCount.toString())) {

                            trayNo = sdf.format(new Date()) + new Random().nextInt(9) + packMessage.getUser().getsCode() + String.format("%04d", 1);

                            logicBean.setTrayNumber(trayNo);
                        } else {
                            trayCount = trayCount.add(new BigInteger("1"));
                            trayNo = trayCount.toString();
                            logicBean.setTrayNumber(trayNo);
                        }
                        String reviewId = "" + UUID.randomUUID().toString() + "";
                        logicBean.setReviewId(reviewId);
                    }
                } else {
                    //生产托盘号，按天重复生成
                    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
                    String traySqlCountResult = this.carDataMapper.selectTraySqlCount(logicBean.getsName(), userCode, sdf.format(new Date()));
                    BigInteger trayCount = null;
                    if (StringUtil.isEmpty(traySqlCountResult)) {
                        trayCount = new BigInteger("1");
                    } else {
                        trayCount = new BigInteger(traySqlCountResult);
                    }
                    if ("1".equals(trayCount.toString())) {

                        trayNo = sdf.format(new Date()) + new Random().nextInt(9) + packMessage.getUser().getsCode() + String.format("%04d", 1);
                        logicBean.setTrayNumber(trayNo);
                    } else {
                        trayCount = trayCount.add(new BigInteger("1"));
                        trayNo = trayCount.toString();
                        logicBean.setTrayNumber(trayNo);
                    }
                    String reviewId = "" + UUID.randomUUID().toString() + "";
                    logicBean.setReviewId(reviewId);
                    //TODO 20201010 CJM
                }
                String prodSpec = "1";//prod2.divide(prod1).setScale(1,     BigDecimal.ROUND_HALF_UP).toString();
                //TODO 20201010 CJM
                if (StringUtil.isNull(cache)) {
                    if (trayNo == "1") {
                        //生产托盘号，按天重复生成
                        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
                        String traySqlCountResult = this.carDataMapper.selectTraySqlCount(logicBean.getsName(), userCode, sdf.format(new Date()));
                        BigInteger trayCount = null;
                        if (StringUtil.isEmpty(traySqlCountResult)) {
                            trayCount = new BigInteger("1");
                        } else {
                            trayCount = new BigInteger(traySqlCountResult);
                        }
                        if ("1".equals(trayCount.toString())) {

                            trayNo = sdf.format(new Date()) + new Random().nextInt(9) + packMessage.getUser().getsCode() + String.format("%04d", 1);
                            logicBean.setTrayNumber(trayNo);
                        } else {
                            trayCount = trayCount.add(new BigInteger("1"));
                            trayNo = trayCount.toString();
                            logicBean.setTrayNumber(trayNo);
                        }

                        String reviewId = "" + UUID.randomUUID().toString() + "";
                        logicBean.setReviewId(reviewId);
                    }
                    int rowtray = 0;
                    try {


                        rowtray = this.carDataMapper.insertparamtray(logicBean, trayNo, prodSpec, userCode);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (rowtray <= 0) {
                        System.out.println("checkWuLiuFaHuoByBarcodeFirst生产托盘号" + trayNo);
                        rowtray = this.carDataMapper.insertparamtray(logicBean, String.valueOf(new BigInteger(trayNo).add(new BigInteger(String.valueOf(new Random().nextInt(9))))), prodSpec, userCode);
                        if (rowtray <= 0) {
                            System.out.println("checkWuLiuFaHuoByBarcodeFirst生产托盘号" + trayNo);
                            cacheService.cleanCommonCache(logicBean.getsName() + userCode + "trayNo");
                            throw new PDAException("复核失败，托盘数据未生成，请退出页面重试！");
                        }
                    }


                }

                logicBean.setTrayDesc(prodSpec);
                // logicBean.setScanners(packMessage.getUser().getsCode());
                rowdetail = this.carDataMapper.updateSqlDetail(logicBean, mBarcode, trayNo, packMessage.getUser());

                if (rowdetail <= 0) {
                     int  updatedata =this.insertData(logicBean, packMessage.getUser());
                     if (updatedata>0){
                         int rowdetail2 =this.carDataMapper.updateSqlDetail(logicBean,mBarcode,trayNo,packMessage.getUser());
                         if (rowdetail2<=0){
                             throw new PDAException("未复核到相关物流码，确认物流码已出标签后继续扫描或者手动更新数据，当前物流码系统拉取到预出日期为：" /*+ sqldefoutdate*/);
                         }
                         this.wuliuRedis("HJ");
                     }else {
                         throw new PDAException("未复核到相关物流码，确认物流码已出标签后继续扫描或者手动更新数据，当前物流码系统拉取到预出日期为：" /*+ sqldefoutdate*/);
                     }

                }

            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
            String todayvalue = sdf.format(new Date());

            //查询当前托盘已扫描的箱数
            if (redisUtil.hasKey(logicBean.getTrayNumber() + "increcount")) {
                if (rowdetail > 0) {
                    redisUtil.incr(logicBean.getTrayNumber() + "increcount", 1);
                    redisUtil.expire(logicBean.getTrayNumber() + "increcount", reidsexpire);
                }
                Integer scanTrayBoxCount = (Integer) redisUtil.get(logicBean.getTrayNumber() + "increcount");
                logicBean.setTrayDesc(scanTrayBoxCount.toString());
            } else {
                Integer scanTrayBoxCount = this.carDataMapper.selectCountsqlTrayDesc(logicBean);
                redisUtil.incr(logicBean.getTrayNumber() + "increcount", scanTrayBoxCount);
                redisUtil.expire(logicBean.getTrayNumber() + "increcount", reidsexpire);
                logicBean.setTrayDesc(scanTrayBoxCount.toString());
            }
            //查询已扫描总的箱数
            if (redisUtil.hasKey(logicBean.getsName() + "snamecount" + todayvalue)) {
                if (rowdetail > 0) {
                    redisUtil.incr(logicBean.getsName() + "snamecount" + todayvalue, 1);
                    redisUtil.expire(logicBean.getsName() + "snamecount" + todayvalue, reidsexpire);
                }
                Integer detailBoxCount = (Integer) redisUtil.get(logicBean.getsName() + "snamecount" + todayvalue);
                logicBean.setTrayDescAll(detailBoxCount.toString());
            } else {
                Integer detailBoxCount = this.carDataMapper.selectsqlreviewTrayDesc(logicBean);
                logicBean.setTrayDescAll(detailBoxCount.toString());
                redisUtil.incr(logicBean.getsName() + "snamecount" + todayvalue, detailBoxCount);
                redisUtil.expire(logicBean.getsName() + "snamecount" + todayvalue, reidsexpire);
            }
            //查询总共该型号多少箱
            //TODO cjm先查询总表
            // ReviewAll  reviewAll   =this.carDataMapper.selectsqlReviewAllQuery(logicBean);

            //查询总共该客户多少箱
            if (redisUtil.hasKey(logicBean.getsName() + "allqtydesc" + todayvalue)) {
                if (rowdetail > 0) {
                    redisUtil.incr(logicBean.getsName() + "allqtydesc" + todayvalue, 1);
                    redisUtil.expire(logicBean.getsName() + "allqtydesc" + todayvalue, reidsexpire);
                }
                Integer allqtydesc = (Integer) redisUtil.get(logicBean.getsName() + "allqtydesc" + todayvalue);
                logicBean.setAllQtyDesc(allqtydesc.toString());
            } else {
                Integer allqtydesc = this.carDataMapper.countReviewAllQuery(logicBean);
                logicBean.setAllQtyDesc(allqtydesc.toString());
                redisUtil.incr(logicBean.getsName() + "allqtydesc" + todayvalue, allqtydesc);
                redisUtil.expire(logicBean.getsName() + "allqtydesc" + todayvalue, reidsexpire);
            }
            logicBean.setAllQty("0"/*reviewAll.getAllQty().toString()*/);
            logicBean.setProdName("");
            obj = (JSONObject) JSONObject.toJSON(logicBean);
            if (rowdetail > 0) {
                if (!redisUtil.hasKey(logicBean.getTrayNumber() + "sname")) {
                    redisUtil.set(logicBean.getTrayNumber() + "sname", logicBean.getsName(), reidsexpire);
                }
                redisUtil.set(logicBean.getLogisticNo() + "rechekflag", logicBean.getTrayNumber(), reidsexpire);
                redisUtil.sSetAndTime(logicBean.getTrayNumber() + "details", reidsexpire, logicBean.getLogisticNo() + "/" + packMessage.getUser().getsCode());
                redisUtil.set(logicBean.getLogisticNo() + "rechekflag", logicBean.getTrayNumber(), reidsexpire);
            }
            logger.debug("第一次扫描条码：" +  obj.toString());
            return obj;
        } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException(e.getMessage());

        }

    }



    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<JSONObject> descGet(PackMessageByWuLiu packMessage) {
        String  sName = packMessage.getsName();
        String defOutDate = packMessage.getDefOutDate();
        List<JSONObject> list = new ArrayList<JSONObject>();
        try {
            //TODO 获取未复核数据
            List<Map> listTemp = this.carDataMapper.descGet(sName,defOutDate);
            if (StringUtil.isEmpty(listTemp)){
                list = new ArrayList<>();
                return list;
            }
            for (Map map : listTemp){
                list.add(new JSONObject(map));
            }

        } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException("暂无未复核的数据提供！");
        }
        return list;

    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<Map> selectSname(PackMessageByWuLiu packMessage) {
        if (StringUtil.isEmpty(packMessage.getTime())) {
            throw new PDAException("时间为空，请确认！");
        }
        return carDataMapper.selectSname(packMessage.getsName(), packMessage.getTime());
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<Map> selectTray(PackMessageByWuLiu packMessage) {
        if (StringUtil.isEmpty(packMessage.getsName()) && StringUtil.isEmpty(packMessage.getTime())) {
            throw new PDAException("客户或时间为空，无法获取托盘号数据！");
        }
        return this.carDataMapper.selectTray(packMessage.getsName(), packMessage.getTime(), packMessage.getUser().getsCode());
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public void checkWuliuBarCodeFlag(PackMessageByWuLiu packMessage) {
        String barcode = packMessage.getBarcode();
        //先检查是否复核过
        if (StringUtil.isNotEmpty(barcode)) {
            if (redisUtil.hasKey(barcode + "rechekflag")) {
                String traynumbertemp = (String) redisUtil.get(barcode + "rechekflag");
                if (!packMessage.getTrayNumber().equals(traynumbertemp)) {
                    throw new PDAException("已复核过,且托盘号不一致" + traynumbertemp + "，当前托盘号为：" + packMessage.getTrayNumber());
                }
                throw new PDAException("当前物流码：" + barcode + ",已复核过!");
            }

            int fuheFlag = this.carDataMapper.countFuHeBybarCode(barcode);
            if (fuheFlag > 0) {
                if (StringUtil.isNotEmpty(packMessage.getTrayNumber())) {
                    String traynumbertemp = this.carDataMapper.countFuHeBybarCodetn(barcode);
                    if (!packMessage.getTrayNumber().equals(traynumbertemp)) {
                        throw new PDAException("已复核过,且托盘号不一致" + traynumbertemp + "，当前托盘号为：" + packMessage.getTrayNumber());
                    }
                }
                throw new PDAException("当前物流码：" + barcode + ",已复核过!");
            }
        }
    }


    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<HashMap> countAllDescBySname(PackMessageByWuLiu packMessage) {
        String sname = packMessage.getsName();
        String defOutDate = packMessage.getDefOutDate();
        List<HashMap> temp = carDataMapper.countAllDescBySname(sname, defOutDate);
        if (StringUtil.isEmpty(temp)) {
            return temp;
        }
        //TODO CJM
        List<HashMap> hashMap = new ArrayList<>();
        for (HashMap map : temp) {

        }
        return temp;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public LogicBean counthasscanDEtail(PackMessageByWuLiu packMessage) {
        String traynumber = packMessage.getTrayNumber();
        if (StringUtil.isEmpty(traynumber)) {
            throw new PDAException("托盘号不存在，不能并盘");
        }
        LogicBean logicBean = new LogicBean();
        String trayDescAll = carDataMapper.counthasscanDEtailAll(traynumber);
        logicBean.setTrayDescAll(trayDescAll);
        String trayDesc = carDataMapper.counthasscanDEtail(traynumber);
        logicBean.setTrayDesc(trayDesc);
        if (redisUtil.hasKey(traynumber + "increcount")) {
            Integer trayDescredis = (Integer) this.redisUtil.get(traynumber + "increcount");
            if (!Integer.valueOf(trayDesc).equals(trayDescredis)) {
                logicBean.setTrayDesc("(无效打印)暂存的计数：" + trayDescredis + "，与已出库数：" + trayDesc + ",不一致，请等待出库程序消费完成或者重新点击确认！");
                System.out.println("补偿判断redisUtil.hasKey(traynumber+\"details\")" + redisUtil.hasKey(traynumber + "details"));
                if (redisUtil.hasKey(traynumber + "details")) {
                    Set<Object> set = redisUtil.sGet(traynumber + "details");
                    for (Object set1 : set) {
                        System.out.println("details----------------------" + set1);
                        try {
                            int des = this.carDataMapper.updateSqlDetailredis(traynumber, set1.toString().split("/")[0], set1.toString().split("/")[1]);
                            System.out.println("redisdetail补偿" + des);
                            logger.debug("redisdetail补偿" + des);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }

                if (redisUtil.hasKey(traynumber + "printreply")) {

                    Integer printreply = (Integer) this.redisUtil.get(traynumber + "printreply");
                    logger.debug("打印重试次数printreply" + printreply);
                    if (printreply > 5) {
                        logicBean.setTrayDesc(trayDesc + "(重置)暂存的计数已被重置为当前已出库数");
                        redisUtil.del(traynumber + "increcount");
                        redisUtil.incr(traynumber + "increcount", Integer.valueOf(trayDesc));
                        redisUtil.expire(traynumber + "increcount", reidsexpire);
                    }
                    redisUtil.incr(traynumber + "printreply", 1);
                    redisUtil.expire(traynumber + "printreply", reidsexpire);
                } else {
                    redisUtil.incr(traynumber + "printreply", 1);
                    redisUtil.expire(traynumber + "printreply", reidsexpire);
                    logger.debug("打印重试次数printreply" + 1);
                }


            }

        }

        return logicBean;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<HashMap> selectTrayDetailByTrayNo(PackMessageByWuLiu packMessage) {
        String traynumber = packMessage.getTrayNumber();
        if (StringUtil.isEmpty(traynumber)) {
            throw new PDAException("托盘号不存在！");
        }
        return this.carDataMapper.selectTrayDetailByTrayNo(traynumber);
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject createTrayNumber(PackMessageByWuLiu packMessage) {
        JSONObject obj = new JSONObject();
        String trayNo = "1";
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        //sdf.format(new java.util.Date()
        HashMap traynotemp = this.carDataMapper.selectdetailSqlCByCode(packMessage.getUser().getsCode());
        if (StringUtil.isNotEmpty(traynotemp)) {
            obj.put("res", "当前托盘未并盘！(" + traynotemp.get("CUSTNAME") + ")");
            obj.put("trayNumber", traynotemp.get("TRAYNUMBER"));
            obj.put("sName", traynotemp.get("CUSTNAME"));
            return obj;
        }


        String traySqlCountResult = this.carDataMapper.selectTraySqlCountre(packMessage.getUser().getsCode(), sdf.format(new Date()));
        System.out.println("createTrayNumber-----traySqlCountResult-----------" + traySqlCountResult);
        BigInteger trayCount = null;
        if (StringUtil.isEmpty(traySqlCountResult)) {
            trayCount = new BigInteger("1");
        } else {
            trayCount = new BigInteger(traySqlCountResult);
        }
        if ("1".equals(trayCount.toString())) {
            trayNo = sdf.format(new Date()) + new Random().nextInt(9) + packMessage.getUser().getsCode() + String.format("%04d", 1);
        } else {
            trayCount = trayCount.add(new BigInteger("1"));
            trayNo = trayCount.toString();
        }
        try {

          /*  int trayCounttemp = this.carDataMapper.counttrayExist(trayNo);
            if (trayCounttemp>1){
                SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
                trayNo = sdf.format(new java.util.Date()) + new Random().nextInt(9999) + packMessage.getUser().getsCode() + String.format("%04d", 1);
            }*/
            int count = 0;
            try {

                count = this.carDataMapper.createTrayNumber(trayNo, packMessage.getUser().getsCode());

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (count <= 0) {
                System.out.println("createTrayNumber-----traySqlCountResult-----------" + traySqlCountResult);
                int counttn = this.carDataMapper.createTrayNumber(String.valueOf(new BigInteger(trayNo).add(new BigInteger(String.valueOf(new Random().nextInt(9))))), packMessage.getUser().getsCode());
                if (counttn <= 0) {
                    System.out.println("createTrayNumber-----traySqlCountResult-----------" + traySqlCountResult);
                    throw new PDAException("托盘号生成失败，退出重试！");
                }
            }
        } catch (Exception e) {
            throw new PDAException("托盘号生成失败，退出重试！");
        }
        obj.put("trayNumber", trayNo);
        return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public HashMap huizongcustName(PackMessageByWuLiu packMessage) {
        String sName = packMessage.getsName();
        if (StringUtil.isEmpty(sName)) {
            throw new PDAException("客户未填写！");
        }
        HashMap map = new HashMap();
        //查询已扫描总的箱数
        Integer detailBoxCount = this.carDataMapper.selectsqlreviewsName(sName);
        map.put("ALLSCAN", detailBoxCount);
        String allqtydesc;
        Object cache = cacheService.getCommonCache(sName + "allqty");
        if (StringUtil.isNotNull(cache)) {
            allqtydesc = cache.toString();
        } else {
            String defOutDate = this.carDataMapper.selectLastDateBySname(sName);
            if (StringUtil.isEmpty(defOutDate)) {
                throw new PDAException("当天无数据！");
            }
            allqtydesc = this.carDataMapper.countReviewAllQuerysname(sName, defOutDate);
            cacheService.setCommonCache(sName + "allqty", allqtydesc);
        }
        map.put("ALLDESC", allqtydesc);
        return map;
    }


    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<JSONObject> requestDeliveryDetail(PackMessageByWuLiu packMessage) {
        String  barcode = packMessage.getBarcode();
        List<JSONObject> list = new ArrayList<JSONObject>();
        if ("54545".equals(barcode)) {
            return list;
        }
        String sname = packMessage.getsName();
        if (StringUtil.isNotEmpty(sname)) {
            Object cache = cacheService.getCommonCache(sname + "DDetail");
            if (StringUtil.isNotNull(cache)) {
                return (List<JSONObject>) cacheService.getCommonCache(sname + "DDetail");
            }
        }
        try {
            //TODO 复合后的数据
            List<Map> listTemp = this.carDataMapper.requestDeliveryDetail(barcode);
            if (StringUtil.isEmpty(listTemp)){
                list = new ArrayList<>();
                return list;
            }
            for (Map map : listTemp){
              //  JSONObject jsonObject = JSONObject.p(map);
                list.add(new JSONObject(map));
            }
        } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            //throw new PDAException("数据发生错误，请再操作一次以便系统更正错误数据！");
        }
        if (StringUtil.isNotEmpty(sname)) {
            cacheService.setCommonCache(sname + "DDetail", list);
        }
            return list;
    }


    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public String compensateTrayNo(String trayNumber) {
        if (StringUtil.isNotEmpty(trayNumber)) {
            Set<Object> settask = redisUtil.sGet(trayNumber + "details");
            System.out.println(settask + "/////" + DateUtils.getTimeSSS());
            StringBuffer sb = new StringBuffer("补偿信息：" + trayNumber + "[");
            for (Object set : settask) {
                System.out.println("details----------------------" + set);
                try {
                    int des = this.carDataMapper.updateSqlDetailredistime(trayNumber, set.toString().split("/")[0], set.toString().split("/")[1]);
                    System.out.println("redisdetail补偿" + des);
                    sb.append(set + "//");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sb.append("]");
            }
            return sb.toString();
        }

        return "HJ";
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    @Async(value = "hjSimpleExecutor")
    public void compensateTrayNotask() {
        Set<String> keys = redisUtil.keys("*details");
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Set<Object> settask = redisUtil.sGet(key);
            System.out.println(key + "/////" + settask + "/////" + DateUtils.getTimeSSS());
            for (Object set2 : settask) {
                System.out.println("details----------------------" + set2);
                try {
                    int des = this.carDataMapper.updateSqlDetailredis(key.replaceAll("details", ""), set2.toString().split("/")[0], set2.toString().split("/")[1]);

                    System.out.println("redisdetail补偿" + des);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }


    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    @Async(value = "hjSimpleExecutor")
    public void wuliuRedis(String id) {

        List<LogicBean> logicBeans = this.carDataMapper.selectBaseLogicBeanSByMBarcodesecond();
        if (StringUtil.isNotEmpty(logicBeans)) {
            for (LogicBean logicBean : logicBeans) {
                if (!redisUtil.hasKey(logicBean.getLogisticNo())) {
                    redisUtil.set(logicBean.getLogisticNo(), JSONUtil.toJsonStr(logicBean), reidsexpire);
                }
            }
            this.selectoccode(logicBeans);
            System.out.println("批次跑缓存服务");
        }

    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    @Async(value = "hjSimpleExecutor")
    public void selectoccode(List<LogicBean> logicBeans) {
        //复核箱码和条码是否贴错
        for (LogicBean logicBean : logicBeans) {
            if (!redisUtil.hasKey(logicBean.getLogisticNo() + "rechekflag")) {
                ProdPack prodPack = null;
                if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo())) {
                    prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo())), ProdPack.class);
                } else {
                    prodPack = this.carDataMapper.selectprodPackpckConfirm(logicBean.getProdNo(), logicBean.getOrgNo());
                    if (null == prodPack) {
                        break;
                    }
                    redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo(), JSONUtil.toJsonStr(prodPack), reidsexpire);
                }
                //开始比对
                //TODO 20201226
                if (new Integer(prodPack.getPckQty()).equals(new Integer(logicBean.getLogisticQty()))) {
                    logicBean.setPckBarcode(prodPack.getPckBarcode());
                    logicBean.setPckQty(prodPack.getPckQty().toString());
                    redisUtil.set(logicBean.getLogisticNo(), JSONUtil.toJsonStr(logicBean), reidsexpire);
                } else {
                    redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo() + "like");
                    redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo());
                }
            }
        }
    }


    /**
     * 二次扫描及后续扫描
     * @param packMessage
     * @return
     */
    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject checkWuLiuFaHuoByBarcode(PackMessageByWuLiu packMessage) {
        String mBarcode = packMessage.getBarcode();
        String mPckBarCode = packMessage.getMpckBarCode();
        String sName = packMessage.getsName();
        String trayNumber =packMessage.getTrayNumber();
        JSONObject obj = new JSONObject();
        LogicBean logicBean = null;
        if (redisUtil.hasKey(mBarcode)) {
            //TODO 20201226
            logicBean = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(mBarcode)), LogicBean.class);
        } else {
            logicBean = this.carDataMapper.selectBaseLogicBeanByMBarcodesecond(mBarcode);
            if (null == logicBean) {
                throw new PDAException("当前物流码：" + mBarcode + ",不存在，请确认！");
            }
            logicBean.setLogisticNo(mBarcode);
            redisUtil.set(mBarcode, JSONUtil.toJsonStr(logicBean), reidsexpire);
        }
        //复核箱码和条码是否贴错
        if (!mPckBarCode.equals(logicBean.getPckBarcode())) {

            ProdPack prodPack = null;
            if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo())) {
                prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo())), ProdPack.class);

            } else {
                prodPack = this.carDataMapper.selectprodPackQueryByParam(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                if (null == prodPack) {
                    if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo() + "like")) {
                        prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo() + "like")), ProdPack.class);
                    } else {
                        prodPack = carDataMapper.selectprodPackQueryByParamlike(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                        if (null == prodPack) {
                            throw new PDAException("second:当前外箱码不匹配，请人工核查外箱与物流码一致性！");
                        }
                        redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo() + "like", prodPack, reidsexpire);
                    }

                } else {
                    redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo(), prodPack, reidsexpire);
                }
        }
            if (!mPckBarCode.equals(prodPack.getPckBarcode())) {
                redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo());
                redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo() + "like");
                throw new PDAException("second:当前外箱码不匹配，请人工核查外箱与物流码一致性！");
            }

        //开始比对
        //TODO 20201226
            if (!new Integer(prodPack.getPckQty()).equals(new Integer(logicBean.getLogisticQty()))) {
                if (redisUtil.hasKey(logicBean.getProdNo() + logicBean.getOrgNo() + "like")) {
                    prodPack = JSONUtil.toBean(JSONUtil.parseObj(redisUtil.get(logicBean.getProdNo() + logicBean.getOrgNo() + "like")), ProdPack.class);
                } else {
                    prodPack = carDataMapper.selectprodPackQueryByParamlike(mPckBarCode, logicBean.getProdNo(), logicBean.getOrgNo());
                }
                if (null == prodPack) {
                    throw new PDAException("secondss:当前外箱码不匹配，请人工核查外箱与物流码一致性！");
                } else {
                    redisUtil.set(logicBean.getProdNo() + logicBean.getOrgNo() + "like", prodPack, reidsexpire);
                    if (!new Integer(prodPack.getPckQty()).equals(new Integer(logicBean.getLogisticQty()))) {
                        redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo() + "like");
                        redisUtil.del(logicBean.getProdNo() + logicBean.getOrgNo());
                        throw new PDAException("当前：" + logicBean.getOrgNo() + "当前外箱对应最大规格数量：" + prodPack.getPckQty() + "与物流码对应数量需求" + logicBean.getLogisticQty() + "不匹配，请联系相关人员!");
                    }
                }
            }
            logicBean.setPckQty(prodPack.getPckQty().toString());
        }
        //比对完成，开始数据更新
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String todayvalue = sdf.format(new Date());
        // System.out.println("发送消息前判断" + logicBean.getLogisticNo() + ":" + FastJsonUtils.getBeanToJson(logicBean));

        if (StringUtil.isEmpty(logicBean.getTrayNumber())) {
            if (StringUtil.isEmpty(trayNumber)) {
                throw new PDAException("当前物流码：" + mBarcode + "未接收到托盘数据，请再试一次！" + trayNumber);
            }
            if (StringUtil.isNumeric(trayNumber)) {
                throw new PDAException("当前托盘号非数字类型，请返回界面重新进入！" + trayNumber);
            }
            logicBean.setTrayNumber(trayNumber);
            //先查询箱规
            if (!sName.trim().equals(logicBean.getsName().trim())){
               // System.out.println("客户比较"+trayNumber+logicBean.getsName());
                if (StringUtil.isNotEmpty(sName)) {
                    throw new PDAException("当前货物属于:" + logicBean.getsName().trim() + ",托盘现有客户为：" + sName + "，请先将当前托盘结束！");
                }else {
                    String snameTemp = null;
                    if (redisUtil.hasKey(logicBean.getTrayNumber() + "sname")) {
                        snameTemp = (String) redisUtil.get(logicBean.getTrayNumber() + "sname");
                    } else {
                        snameTemp = this.carDataMapper.selectTraySName(trayNumber);
                    }
                        if (StringUtil.isNotEmpty(snameTemp)) {
                            if (!snameTemp.trim().equals(logicBean.getsName().trim())){
                                throw new PDAException("当前货物属于:" + logicBean.getsName().trim() + ",托盘现有客户为：" + snameTemp + "，请先将当前托盘结束！");
                            }
                        }
                }
            }
            if (redisUtil.hasKey(trayNumber + "status")) {
                throw new PDAException("当前托盘：" + trayNumber + "已并盘,不允许追加件数！");
            } else {
                String traystatus = this.carDataMapper.selecttraystatus(trayNumber);
                if ("2".equals(traystatus)) {
                    redisUtil.set(trayNumber + "status", traystatus, reidsexpire);
                }
            }

            redisUtil.incr(logicBean.getTrayNumber() + "increcount", 1);
            redisUtil.expire(logicBean.getTrayNumber() + "increcount", reidsexpire);
            redisUtil.incr(logicBean.getsName() + "snamecount" + todayvalue, 1);
            redisUtil.expire(logicBean.getsName() + "snamecount" + todayvalue, reidsexpire);
            redisUtil.incr(logicBean.getsName() + "allqtydesc" + todayvalue, 1);
            redisUtil.expire(logicBean.getsName() + "allqtydesc" + todayvalue, reidsexpire);

            logicBean.setTrayNumber(trayNumber);
            logicBean.setScanners(packMessage.getUser().getsCode());
            logicBean.setScannName(packMessage.getUser().getsName());
            logicBean.setLogisticNo(mBarcode);
            //mq
           /* msgService.sendDelayMsgToMQ(MqConstant.WMS_DELAY_EXCHANGE, MqConstant.WMS_DELAY_KEY, FastJsonUtils.getBeanToJson(logicBean),
                    1);//0.5秒钟后执行*/
            System.out.println("发送消息：" + logicBean.getLogisticNo() + ":" + FastJsonUtils.getBeanToJson(logicBean));
            msgService.sendDelayMsgToMQ(MqConstant.SYS_ORDER_DELAY_EXCHANGE, MqConstant.SYS_ORDER_DELAY_KEY, FastJsonUtils.getBeanToJson(logicBean), 54);//30秒钟后执行
            redisUtil.set(logicBean.getLogisticNo() + "rechekflag", logicBean.getTrayNumber(), reidsexpire);
            redisUtil.set(logicBean.getLogisticNo(), JSONUtil.toJsonStr(logicBean), reidsexpire);

            /*int rowdetail = this.carDataMapper.updatesqlDetailSecond(logicBean, mBarcode, trayNumber, packMessage.getUser());
                if (rowdetail <= 0) {
                    int  updatedata =this.insertData(logicBean, packMessage.getUser());
                    if (updatedata>0){
                        int rowdetail2 = this.carDataMapper.updatesqlDetailSecond(logicBean, mBarcode, trayNumber, packMessage.getUser());
                        if (rowdetail2<=0){
                            throw new PDAException("未复核到相关物流码，请确保日期并已出标签后在操作一次，当前物流码系统拉取到预出日期为：" + logicBean.getDefOutDate());
                        }
                    }else {
                        throw new PDAException("未拉取到明细数据，请确保日期并已出标签后在操作一次，当前物流码系统拉取到预出日期为：" + logicBean.getDefOutDate());
                    }
                }*/


        } else {
            if (!logicBean.getTrayNumber().equals(trayNumber)) {
                throw new PDAException("已复核，托盘号为：" + logicBean.getTrayNumber());
            }
            }
        //查询当前托盘已扫描的箱数 TODO 20201226
        if (redisUtil.hasKey(logicBean.getTrayNumber() + "increcount")) {
            Integer scanTrayBoxCount = (Integer) redisUtil.get(logicBean.getTrayNumber() + "increcount");
            logicBean.setTrayDesc(scanTrayBoxCount.toString());
        } else {
            Integer scanTrayBoxCount = this.carDataMapper.selectCountsqlTrayDesc(logicBean);
            logicBean.setTrayDesc(scanTrayBoxCount.toString());
            redisUtil.incr(logicBean.getTrayNumber() + "increcount", scanTrayBoxCount);
            redisUtil.expire(logicBean.getTrayNumber() + "increcount", reidsexpire);
        }

        //查询已扫描总的箱数 TODO 20201226
        if (redisUtil.hasKey(logicBean.getsName() + "snamecount" + todayvalue)) {
            Integer detailBoxCount = (Integer) redisUtil.get(logicBean.getsName() + "snamecount" + todayvalue);
            logicBean.setTrayDescAll(detailBoxCount.toString());
        } else {
            Integer detailBoxCount = this.carDataMapper.selectsqlreviewTrayDesc(logicBean);
            logicBean.setTrayDescAll(detailBoxCount.toString());
            redisUtil.incr(logicBean.getsName() + "snamecount" + todayvalue, detailBoxCount);
            redisUtil.expire(logicBean.getsName() + "snamecount" + todayvalue, reidsexpire);
        }
        //查询总共该客户多少箱
        if (redisUtil.hasKey(logicBean.getsName() + "allqtydesc" + todayvalue)) {
            Integer allqtydesc = (Integer) redisUtil.get(logicBean.getsName() + "allqtydesc" + todayvalue);
            logicBean.setAllQtyDesc(allqtydesc.toString());
            } else {
            Integer allqtydesc = this.carDataMapper.countReviewAllQuery(logicBean);
            logicBean.setAllQtyDesc(allqtydesc.toString());
            redisUtil.incr(logicBean.getsName() + "allqtydesc" + todayvalue, allqtydesc);
            redisUtil.expire(logicBean.getsName() + "allqtydesc" + todayvalue, reidsexpire);
            }
            obj = (JSONObject) JSONObject.toJSON(logicBean);
        redisUtil.sSetAndTime(trayNumber + "details", reidsexpire, logicBean.getLogisticNo() + "/" + packMessage.getUser().getsCode());
            return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional( )
    public JSONObject confirmTray(PackMessageByWuLiu packMessage) {
        String trayNumber =packMessage.getTrayNumber();

        JSONObject obj = new JSONObject();
        try {
            String sname = this.carDataMapper.selectSnameBy(trayNumber);
            int rowUptray = this.carDataMapper.updatesqlUptrayConfirm(trayNumber, sname);
            if (rowUptray <= 0) {
                this.cacheService.setCommonCache(trayNumber, "2");
                throw new PDAException("当前托盘：" + trayNumber + ",已确认过，无需重复确认！");
            }
            this.cacheService.setCommonCache(trayNumber, "2");

            //  this.carDataMapper.updateSqlBytrayNumber(trayNumber)
            obj.put("httpResponse","当前托盘："+trayNumber+",已完成并板");
            redisUtil.set(trayNumber + "status", "2", reidsexpire);
         } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            if (e instanceof PDAException) {
                throw new PDAException("当前托盘：" + trayNumber + ",已确认过，无需重复确认！");
            }else {
                throw new PDAException("托盘数据更新发生未知错误!");
            }}
            logger.debug(obj.toString());
            return obj;
    }

    public  List<ReviewDetail> getReviewDetail( String trayNumber, String reviewId)  {
        List<ReviewDetail> lists = null;
        try {
            lists = this.carDataMapper.selectReviewDetailList(trayNumber, reviewId);
            if (StringUtil.isEmpty(lists)){
                lists =  new ArrayList<>();
            }
        } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException("复核明细数据正在路上，请稍后！");
        }
            logger.debug(lists.toString());
            return lists;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject delTray(PackMessageByWuLiu packMessage) {
        String trayNumber =packMessage.getTrayNumber();
        JSONObject obj = new JSONObject();
        try {
             //先做查询
             ReviewTray reviewTray   =  this.carDataMapper.trayQuerydel(trayNumber);
             if (null==reviewTray){
                 throw new PDAException("当前托板正在复核中或者不存在!");
            }
            List<ReviewDetail> reviewDetails = this.getReviewDetail(reviewTray.getTrayNo(), reviewTray.getReviewId());
            //再做更新
            for (ReviewDetail reviewDetail:reviewDetails) {
                 int rowUpAll =   this.carDataMapper.updatesqlUpAllDetailSecond(reviewDetail,reviewTray);
                if (rowUpAll <= 0) {
                    throw new PDAException("总表减少失败，请稍后重试!");
                }
            }
            //最后删除
            int rowDeldetail = this.carDataMapper.delsqlDelDetail(trayNumber);
            if (rowDeldetail <= 0) {
                throw new PDAException("无法删除明细数据：" + trayNumber + ",请确认托盘状态是否正常！");
            }
            int rowDeltray = this.carDataMapper.delsqlDelTray(trayNumber);
            if (rowDeltray <= 0) {
                throw new PDAException("无法删除托盘数据：" + trayNumber + ",请确认托盘状态是否正常！");
            }
            obj.put("httpResponse","当前托盘："+trayNumber+",已完成删除操作");
         } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException(e.getMessage());
        }
            logger.debug(obj.toString());
            return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject checkPckBarCode(PackMessageByWuLiu packMessage) {
        String mPckBarcode = packMessage.getMpckBarCode();

        JSONObject obj = new JSONObject();
        //查询是否存在该外箱条码
        logger.debug("1checkPckBarCode："+mPckBarcode);
        Integer sqllppmExist = this.carDataMapper.selectsqllppmcheckPckBarCode(mPckBarcode);
            if (sqllppmExist<=0){
                obj.put("httpError","checkPckBarCode:当前外箱条码未维护，请联系相关人员确认！"+mPckBarcode);
                logger.debug(obj.toString());
                return obj;
            }
        obj.put("httpSuccess","checkPckBarCode:当前外箱条码有数据，成功"+mPckBarcode+sqllppmExist);
        logger.debug("3checkPckBarCode："+obj.toJSONString());

        return obj;
    }

    /**
     * 零散箱自动新增托盘
     * @param packMessage
     * @return
     */
    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject antoCreateWithSurplus(PackMessageByWuLiu packMessage) {
        String barcode = packMessage.getMpckBarCode();
        String userCode = packMessage.getUser().getsCode();
        JSONObject objResult = new JSONObject();
        List<JSONObject> list = requestDeliveryDetail(packMessage);
        try{
            int autoBox = 0;
             for (int i = 0; i <list.size() ; i++) {
                JSONObject obj = list.get(i);
                Integer surplusQty = Integer.parseInt(obj.getString("allQty"))-Integer.parseInt(obj.getString("scanQty"));
                if (surplusQty!=0 && surplusQty < new Integer(obj.getString("prodSpec"))){
                    //先新增托盘
                    //生产托盘号，按天重复生成
                    Integer trayCount = this.carDataMapper.selectTraySqlCountantoCreateWithSurplus();
                    String trayNo ="";
                    if ("1".equals(trayCount.toString()) ) {
                        SimpleDateFormat sdf= new SimpleDateFormat("yyMMdd");
                        trayNo = sdf.format(new Date()) + "" + String.format("%05d", 1);
                    } else {
                        ++trayCount;
                        trayNo = trayCount.toString();
                    }
                    int rowtray = this.carDataMapper.insertsqlTrayantoCreateWithSurplus(obj.get("reviewId"),trayNo,surplusQty,
                            "1","2",userCode,userCode,obj.get("sName"));

                    if (rowtray<=0){
                        throw new PDAException("TRAY未自动累计零散箱" + obj.get("prodName") + "，请确认是否需要累计" + surplusQty + "!");
                    }
                    //在新增明细
                    int rowdetail = this.carDataMapper.insertsqlDetailantoCreateWithSurplus(obj.get("reviewId"), "autoCreate", "autoCreate",
                            trayNo, surplusQty, userCode,  "", obj.get("prodNo"),
                            obj.get("prodName"), "", "",obj.get("sName"));
                    if (rowdetail <= 0) {
                        throw new PDAException("DETAIL未自动累计零散箱" + obj.get("prodName") + "，请确认是否需要累计" + surplusQty + "!");
                    }
                    //最后更新总表
                    int rowUpAll = this.carDataMapper.updatesqlUpAllantoCreateWithSurplus(surplusQty,1,obj.get("prodNo"),obj.get("reviewId"));
                    if (rowUpAll <= 0) {
                        throw new PDAException("ALL未自动累计零散箱" + obj.get("prodName") + "，请确认是否需要累计" + surplusQty + "!");
                    }
                    ++autoBox;
                }
            }
             objResult.put("autoBox",autoBox);
        } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException(e.getMessage());
        }
            logger.debug(objResult.toString());
            return objResult;

    }

    /**
     * getComfirmLcl
     * @param packMessage
     * @return
     */
    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<JSONObject> getComfirmLcl(PackMessageByWuLiu packMessage) {
        String  trayNumber = packMessage.getTrayNumber();
            return  this.carDataMapper.selectgetComfirmLcl(trayNumber);
          }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject submitComfirmLcl(PackMessageByWuLiu packMessage) {
        String trayNumber =packMessage.getTrayNumber();
        String message =packMessage.getMessage();
        String userCode = packMessage.getUser().getsCode();
        Integer sumLcl = packMessage.getPos();
        List<LogicBean> logiConfirms = new ArrayList<>();
        String[] comfirms = message.split(",");
        for (int i =0 ; i<comfirms.length;i++){
            int index=comfirms[i].lastIndexOf("/");
            String confirmBefore=comfirms[i].substring(0,index);
            String confirmAfter=comfirms[i].substring(index+1);
            LogicBean logicTemp  = new LogicBean();
            logicTemp.setProdName(confirmBefore);
            logicTemp.setLogisticQty(confirmAfter);
            logiConfirms.add(logicTemp);
        }
        JSONObject obj = new JSONObject();
        try {
             //先做查询
             ReviewTray reviewTray   =this.carDataMapper.selecttrayQuerysubmitComfirmLcl(trayNumber);
             if (null==reviewTray){
                 throw new PDAException("当前托板状态不正常，请稍后重试!");
            }

            StringBuffer prodNames = new StringBuffer("");
            StringBuffer prodNos = new StringBuffer("");
            String orgNo="";
            Integer logisticQty = 0;
            //先更新张总表
            double SCAN_QTY_DESC;
            if (sumLcl==1) {
                SCAN_QTY_DESC = new BigDecimal((float) 1 / logiConfirms.size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }else {
                SCAN_QTY_DESC=0;
            }
            for (int i=0; i<logiConfirms.size() ; i++){
                int rowUpAll = this.carDataMapper.updatesqlUpAllsubmitComfirmLcl(logiConfirms.get(i).getLogisticQty(),SCAN_QTY_DESC,logiConfirms.get(i).getProdName(),reviewTray.getReviewId());
                if (rowUpAll <= 0) {
                    throw new PDAException("手动拼箱失败，请稍后重试!（总表）" + logiConfirms.get(i).getProdName());
                }
                //做查询
                LogicBean logicBean   = this.carDataMapper.selectgetAllResult(logiConfirms.get(i).getProdName(),reviewTray.getReviewId());
                 logiConfirms.get(i).setProdNo(logicBean.getProdNo());
                logiConfirms.get(i).setOrgNo(logicBean.getOrgNo());
                if (i>1){
                    if(orgNo.equals(logicBean.getOrgNo()) ) {
                        throw new PDAException("手动拼箱失败，需合并的型号数据不属于同一仓，不允许合并，请确认！");
                    }
                }
                orgNo = logicBean.getOrgNo();
                //TODO  CJM  orgno 不同
                prodNames.append(logiConfirms.get(i).getProdName()+"/");
                prodNos.append(logicBean.getProdNo()+"/");

                logisticQty=logisticQty+new Integer(logiConfirms.get(i).getLogisticQty());
            }
            //再更新托盘
            int rowUptray = this.carDataMapper.updatesqlUpsubmitComfirmLcl(logisticQty,SCAN_QTY_DESC,trayNumber);
            if (rowUptray <= 0) {
                throw new PDAException("手动拼箱拖失败，请稍后重试（托盘）!" + prodNames);
            }
            //最后做明细的新增
             //创建object数组
            Date utilDate = new Date();
            java.sql.Timestamp sqlDate = new java.sql.Timestamp(utilDate.getTime());
            int rowdetail = this.carDataMapper.insertsqlDetailsubmitComfirmLcl(reviewTray.getReviewId(), sqlDate+"MERGE"+System.nanoTime(), "Union box"+sqlDate,trayNumber,
                    logisticQty.toString(),  userCode, null, SCAN_QTY_DESC, prodNos.toString(),
                    prodNames.toString(), 0, orgNo,reviewTray.getCustName().toString(),"0","手动拼箱");

            if (rowdetail <= 0) {
                throw new PDAException("手动拼箱失败，请稍后重试!（明细）" + prodNames);
            }
            obj.put("sumLcl",sumLcl);
            obj.put("httpResponse","成功：已将数据合并到托盘："+trayNumber);
         } catch (Exception e) {
            logger.debug(e.toString());
            e.printStackTrace();
            throw new PDAException(e.getMessage());
        }
            logger.debug(obj.toString());
            return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject updateDataByCustName(PackMessageByWuLiu packMessage) {
        JSONObject obj = new JSONObject();
        String sName = packMessage.getsName();
        String defOutDate =packMessage.getDefOutDate();
        LogicBean  reviewIdSname = this.carDataMapper.selectreviewIdSqlupdateDataByCustName( sName, defOutDate);
        if (StringUtil.isNotNull(reviewIdSname)) {
            reviewIdSname.setDefOutDate(defOutDate);
            reviewIdSname.setsName(sName);
            int rowall =  this.insertData(reviewIdSname,packMessage.getUser());
             if (rowall<=0){
                 obj.put("httpError", "当前日期：" + defOutDate + ",未拉取到明细数据，请确认日期或者确保已出标签，并重新尝试!");
             } else {
                 this.wuliuRedis("HJ");
                 obj.put("httpResponse", "成功更新数据：" + rowall + "条");
             }

        } else {
            obj.put("httpError", "当前日期：" + defOutDate + ",未拉取到明细数据，请确认日期或者确保已出标签，并重新尝试!");
        }
        logger.debug(obj.toString());
        return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject trayConfirm(PackMessageByWuLiu packMessage) {
        JSONObject obj = new JSONObject();
        String sName = packMessage.getsName();
        String defOutDate =packMessage.getDefOutDate();
        LogicBean  reviewIdSname = this.carDataMapper.selecttrayConfirmByCustName( sName, defOutDate);
        if (StringUtil.isNotNull(reviewIdSname)) {
            reviewIdSname.setDefOutDate(defOutDate);
            ReviewTray reviewTray = this.carDataMapper.selectSqlTrayDesc(reviewIdSname.getTrayNumber());
            obj.put("trayDesc",reviewTray.getScanBox());
            obj.put("trayNumber",reviewIdSname.getTrayNumber());
            obj.put("httpResponse","当前日期："+defOutDate+",当前客户："+sName+",已查询到数据，可以打印托盘号或者继续在本托盘号上复核接下来的数据！");
        } else {
            obj.put("httpError","当前日期："+defOutDate+",当前客户："+sName+",没有未打印的托盘号！");
        }
        logger.debug(obj.toString());
        return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public JSONObject pckConfirm(PackMessageByWuLiu packMessage) {
        JSONObject obj = new JSONObject();
        String mBarcode = packMessage.getBarcode();
        LogicBean  logicBean ;
        logicBean   = this.carDataMapper.selectpckConfirm(mBarcode);
        if(null==logicBean) {
            throw new PDAException("当前物流码" + mBarcode + "未拉取到明细数据，请确保标签已出后重新操作!");
        }
        ProdPack  prodPack   = this.carDataMapper.selectprodPackpckConfirm(logicBean.getProdNo() ,logicBean.getOrgNo() );
        if(null==prodPack){
            throw new PDAException("未成功获取到外箱码，无法手工确认，请联系相关人员维护" + logicBean.getOrgNo() + "SKU!");
        }


        HashMap lmsTemp = this.carDataMapper.selectProdlms(logicBean.getProdNo(), logicBean.getOrgNo());
        if (StringUtil.isNotEmpty(lmsTemp)) {
            String prodNo = prodPack.getProdNo();
            prodPack.setProdNo(prodNo + lmsTemp.get("PRODNAME") + lmsTemp.get("SPEC"));
        }
        obj=(JSONObject) JSONObject.toJSON(prodPack);
        logger.debug(obj.toString());
        return obj;

    }

    @DataBase(DataSourceNames.WMS)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    int insertData(LogicBean logicBean, MgUser user) {

         int countdetail = this.carDataMapper.insertDataDetail(logicBean,user);
        //   int countAll =  this.carDataMapper.insertData(logicBean,user);
         if (countdetail>0 ){
             // this.cacheService.setCommonCache(logicBean.getsName() + "allqty", null);
             return countdetail;
         }
        return countdetail;
    }


}





